import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import Service from '@/public/http/services';
import { Icon, Modal, Form, Input, Select, DatePicker, Radio, Upload } from 'antd';
//@ts-ignore
import LzEditor from 'react-lz-editor';
import style from './index.css';
const { TextArea } = Input;
const { Option } = Select;
const CreateModal: React.FC<any> = ({ formData, visible, title, onOK, onCancel, form, dispatch }) => {

    const [defaultContent, setDefaultContent] = useState('<h3>请输入</h3>');
    useEffect(() => {
        if (visible) {
            setDefaultContent(formData.content || '<h3>请输入</h3>');
            setHtmlContent(formData.content || '<h3>请输入</h3>');
            if (formData && Object.keys(formData).length) {
                const imgs = formData.coverImg.split(',');
                setCurFileList(imgs.map((img, index) => {
                    return {
                        uid: formData.id + index,
                        url: img
                    }
                }));

            }
        }
    }, [visible, formData])
    const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    }

    const { getFieldDecorator } = form;

    const [loading, setLoading] = useState(false);

    const [curFileList, setCurFileList] = useState([]);

    const uploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurFileList(curFileList.concat([{
            uid,
            name,
            url: curFileUrl,
        }] as any));
    }

    const handleChange = (file) => { }

    const [curActionUrl, setCurActionUrl] = useState();
    const [curUploadData, setCurUploadData] = useState({});
    const [curFileUrl, setCurUrl] = useState('');
    const beforeUpload = async (file, fileList) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurUrl(host + '/' + key)
        setCurUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
        });
        return true;
    }

    const removeSuccess = (file) => {
        let list = [];
        for (const item of curFileList) {
            if ((item as any).uid !== file.uid) list.push(item);
        }
        setCurFileList(list);
    }
    /**
     * @desc 文章插图上传配置
     */
    const upload: any = {
        name: 'file',
        action: curActionUrl,//上传接口，成功后返回该图片服务器地址
        listType: 'picture-card',
        headers: {
            authorization: 'authorization-text',
        },
        onSuccess: uploadSuccess,
        onChange: handleChange,
        beforeUpload: beforeUpload,
        onRemove: removeSuccess,
        data: curUploadData,
        multiple: true
    }

    /**
     * editor config
     */
    const [curEditorList, setCurEditorList] = useState([])
    const [htmlContent, setHtmlContent] = useState('');

    const receiveHtml = (content: string) => {
        setHtmlContent(content);
        setCurEditorList([]);
    }

    const handleEditorFileChange = (changedValue) => {
        let { file, fileList } = changedValue;
        for (const item of curEditorList) {
            if ((item as any).uid === file.uid) return;
        }
        const { uid, name } = file;
        setCurEditorList(curEditorList.concat([{
            uid,
            name,
            url: curEditorUrl,
        }] as any));
    }

    const [curEditorActionUrl, setCurEditorActionUrl] = useState();
    const [curEditorUploadData, setCurEditorUploadData] = useState({});
    const [curEditorUrl, setCurEditorUrl] = useState('');
    const editorBeforeUpload = async (file, fileList) => {
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurEditorActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurEditorUrl(host + '/' + key)
        setCurEditorUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
        });
        return true;
    }

    const removeEditorSuccess = (file) => {
        let list = [];
        for (const item of curEditorList) {
            if ((item as any).uid !== file.uid) list.push(item);
        }
        setCurEditorList(list);
    }

    const editorUpload = {
        action: curEditorActionUrl,
        onChange: handleEditorFileChange,
        listType: 'picture',
        data: curEditorUploadData,
        multiple: false,
        beforeUpload: editorBeforeUpload,
        onRemove: removeEditorSuccess,
    }

    return (
        <Modal
            visible={visible}
            title={title}
            okText={'保存'}
            cancelText={'取消'}
            onOk={() => {
                setCurFileList([])
                setCurEditorList([])
                onOK && onOK(form, { files: curFileList, content: htmlContent })
            }}
            onCancel={() => {
                setCurFileList([])
                setCurEditorList([])
                onCancel(form)
            }}
            width={'65%'}
        >
            <Form.Item {...formItemLayout} label={'培训类型'}>
                {
                    getFieldDecorator('type', {
                        initialValue: formData.type,
                        rules: [{ required: true, message: '请选择培训类型' }],
                    })(<Select className={style.w220} placeholder={'请选择培训类型'}>
                        <Option value={1}>线上微课</Option>
                        <Option value={2}>线下培训</Option>
                    </Select>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'培训主题'}>
                {
                    getFieldDecorator('title', {
                        initialValue: formData.title,
                        rules: [{ required: true, message: '请输入培训主题' }],
                    })(<Input placeholder={'请输入培训主题'} />)
                }
            </Form.Item>
            <Form.Item className={style.mb0} {...formItemLayout} label={'封面'}>
                {
                    getFieldDecorator('coverImg', {
                        initialValue: curFileList.length ? (curFileList[0] as any).url : '',
                        rules: [{ required: true, message: '请上传封面' }],
                    })(<Upload
                        {...upload}
                        fileList={curFileList}
                    >
                        <div>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className="ant-upload-text">上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'开始时间'}>
                {
                    getFieldDecorator('startTime', {
                        initialValue: formData && formData.startTime ? moment(formData.startTime, "YYYY-MM-DD") : null,
                        rules: [{ required: true, message: '请选择开始时间' }],
                    })(<DatePicker className={style.w220} format='YYYY-MM-DD' placeholder={'请选择开始时间'} />)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'培训描述'}>
                {
                    getFieldDecorator('summry', {
                        initialValue: formData.summry,
                        rules: [{ required: true, message: '请输入培训描述' }],
                    })(<TextArea placeholder={'请输入培训描述'} />)
                }
            </Form.Item>
            <Form.Item label='培训内容' {...formItemLayout}>
                {getFieldDecorator('content', {
                    // rules: [{ required: true, message: '培训内容' }],
                    initialValue: '',
                })(
                    <LzEditor
                        active={true}
                        importContent={defaultContent}
                        cbReceiver={receiveHtml}
                        uploadProps={{ ...editorUpload, fileList: curEditorList }}
                        video={false}
                        audio={false}
                        lang={'ch'}
                    />
                )}
            </Form.Item>
            <Form.Item {...formItemLayout} label={'是否热门'}>
                {
                    getFieldDecorator('isBanner', {
                        rules: [{ required: true, message: '请选择是否热门' }],
                    })(<Radio.Group name="radiogroup">
                        <Radio value={1}>是</Radio>
                        <Radio value={0}>否</Radio>
                    </Radio.Group>)
                }
            </Form.Item>
        </Modal>
    );
}
const WrappedCreateModal = Form.create<any>({ name: 'modalForm' })(CreateModal);
export default connect((state: any) => {
    return {}
})(WrappedCreateModal);
